package com.woniu.job.controller;

import java.io.File;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.woniu.job.exception.service.NoDefaultResourceException;
import com.woniu.job.exception.service.ResumeWorkIsExistException;
import com.woniu.job.exception.service.ServiceException;
import com.woniu.job.service.IInterviewService;
import org.eclipse.jetty.util.security.Password;
import com.woniu.job.entity.Favorite;
import com.woniu.job.entity.vo.ResultVO;
import com.woniu.job.service.IFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;
import com.woniu.job.entity.ResponseVo;
import com.woniu.job.entity.User;
import com.woniu.job.service.IUserService;
import com.woniu.job.util.RegexUtil;
import com.woniu.job.util.Utils;



/**
 * 用户
 *
 * @author 韦汉强
 */



@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ResponseVo vo;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IFavoriteService iFavoriteService;
    @Autowired
    private IInterviewService iInterviewService;

    /**
     * 进入 注册
     *
     * @return
     */
    @GetMapping("/register")
    public String register() {
        return "register";
    }

    /**
     * 提交注册
     *
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResponseVo formRegister(User user, String password2) {
        if (!RegexUtil.isEmail(user.getEmail())) {
            vo.setCode("500");
            vo.setMeg("邮箱格式错误");
            return vo;
        }
        if (!user.getPassword().equals(password2)) {
            vo.setCode("500");
            vo.setMeg("两次密码输入不一样");
            return vo;
        }
        return iUserService.register(user);
    }

    /**
     * 登录
     *
     * @param user
     * @param
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
   
	public ResponseVo login(User user,String expire,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		vo=iUserService.login(user);
		if(vo.getCode().equals("200")){
			if(expire!=null){
				User user1=(User) vo.getData();
				Cookie cookie=new Cookie("user", user1.getAccount()+"=="+user1.getPassword()+"=="+user1.getId());
				cookie.setMaxAge(Integer.parseInt(expire)*60);
				response.addCookie(cookie);
			}
			session.setAttribute("user", vo.getData());
		}
		return vo;
	}
 


    /**
     * @Description: 用户增加简历收藏
     * @Param: 岗位[id] 用户[user]
     * @return: com.woniu.job.entity.vo.ResultVO
     * @Author: 陈C
     * @Date: 2019/12/26
     */
    @GetMapping("/favo/{id}")
    @ResponseBody
    public ResultVO favoriteAdd(@PathVariable String id, @SessionAttribute User user) {
        Favorite favorite = new Favorite();
        favorite.setUserId(user.getId());
        favorite.setWorkId(id);
        try {
            iFavoriteService.favoriteAdd(favorite);
            return ResultVO.SUC;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.ERROR;
        }
    }

	/**
	* @Description: 查询用户的职位收藏
	* @Param: [model, user]
	* @return: java.lang.String
	* @Author: 陈C
	* @Date: 2019/12/26
	*/
    @GetMapping("/favoAll")
    public String getAllFavorite(Model model, @SessionAttribute User user) {
        model.addAttribute("favoAll",iFavoriteService.getAllFavo(user.getId()));
        return "personal/job_favors";
    }

    /**
    * @Description: 删除用户的收藏
    * @Param: [wordId]
    * @return: com.woniu.job.entity.vo.ResultVO
    * @Author: 陈C
    * @Date: 2019/12/26
    */
    @GetMapping("/delFavo")
	@ResponseBody
	private  ResultVO delFavo(String[] wordId){
    	try {
    		iFavoriteService.delFavo(wordId);
			return  ResultVO.SUC;
		}catch (Exception e){
    		e.printStackTrace();
    		return  ResultVO.ERROR;
		}

	}

	/**
	 * 用户信息
	 * @return
	 */
	@GetMapping("/meg")
	public String userMeg(Model model,HttpSession session) {
		System.out.println(session.getAttribute("user"));
		User user=(User) session.getAttribute("user");
		if(user==null) {
			return "redirect:/";
		}
		model.addAttribute("user",iUserService.findUser(user) );
		System.out.println(iUserService.findUser(user));
		return "personal/user_profile";	
	}
	/**
	 * 上传头像
	 * @return
	 */
	@Value("${images.location}")
	private String path;
	@PostMapping("/userAvatar")
	public String userAvatar(MultipartFile avatarImg,HttpSession session){
		 String filename=avatarImg.getOriginalFilename();
		   //得到文件后缀
		 int a=filename.indexOf(".");
		 String lastfilename=filename.substring(a);
		 String avatar= Utils.getUID();
		 	try{
		         File file=new File(path+ avatar+lastfilename);
		         avatarImg.transferTo(file);
		          User user= (User) session.getAttribute("user");
		          user.setAvatar("/"+avatar+lastfilename);
		          //System.out.println(user.getAvatar());
		          iUserService.updateAvater(user);
		        }catch (Exception e){
		        	e.printStackTrace();
		        }
		        return  "redirect:/user/meg";
	}
	/**
	 * 修改密码
	 * @return
	 */
	@PostMapping("/updatepwd")
	@ResponseBody
	public ResponseVo updatePwd(String oldpassword,String password1,HttpSession session) {
		 User user= (User) session.getAttribute("user");
		 if(!oldpassword.equals(user.getPassword())){
			 vo.setCode("500");
			 vo.setMeg("原始密码错误");
			 return vo;
		 }
		user.setPassword(password1);
		return iUserService.updatePwd(user);
		
	}
	/**
	 * 完善个人信息
	 * 
	 */
	@PostMapping("/updateProfile")
	@ResponseBody
	public ResponseVo updateProfile(User user,HttpSession session) {
		 User user1= (User) session.getAttribute("user");
		 user.setId(user1.getId());
		 //System.out.println(user);
		return iUserService.updateProfile(user);
		
	}


	/**
	* @Description: 投递简历
	* @Param: [user, id]
	* @return: com.woniu.job.entity.vo.ResultVO
	* @Author: 陈C
	* @Date: 2019/12/28
	*/
	@GetMapping("sendResume/{id}")
	@ResponseBody
	public ResultVO sendResume(@PathVariable String id,@SessionAttribute User user){
	    System.out.println(user);
		try {
			iFavoriteService.sendResdResume(user.getId(),id);
			return ResultVO.SUC;
		}catch (ServiceException e){
			e.printStackTrace();
			if(e instanceof ResumeWorkIsExistException){
				return ResultVO.ERROR;
			}else if (e instanceof NoDefaultResourceException){
			    return new ResultVO(333,true,"没有简历");
            }
			return ResultVO.NOTFOUND;
		}

	}


    /**
    * @Description:查看面试邀请
    * @Param: [model, 用户user]
    * @return: java.lang.String
    * @Author: 陈C
    * @Date: 2019/12/30
    */
    @GetMapping("lookResume")
	public String lookResume(Model model, @SessionAttribute User user){
        //根据用户id查询面试表
		model.addAttribute("resumeAll",iFavoriteService.lookResume(user.getId()));
		iFavoriteService.lookResume(user.getId());
        return "personal/interviews";
    }


    /**
    * @Description: 修改面试查看状态
    * @Param: [面试信息id, user]
    * @return: com.woniu.job.entity.vo.ResultVO
    * @Author: 陈C
    * @Date: 2019/12/31
    */
    @GetMapping("updateStutas/{id}")
	@ResponseBody
    public ResultVO updateStutas(@PathVariable  String[] id,@SessionAttribute User user){
    	iInterviewService.updateStutas(id,user.getId());
    	return  ResultVO.SUC;
	}
	

}
